var App = function () {
  //计算是否在优惠时间段
  function timeBetween(start_sale_date, end_sale_date) {
    if (start_sale_date == "") {
      return true
    } else {
      var today = moment().format("YYYY-MM-DD HH:mm");
      var todayDate = moment().format("YYYY-MM-DD");
      return moment(today).isBetween(todayDate + " " + start_sale_date, todayDate + " " + end_sale_date);
    }
  }

  function loadTop() {
    $(".layout>.top").load("../public/public.html", function (responseTxt, statusTxt, xhr) {
      var links = $(".layout>.top li a"),
        index = 0, //默认第一个菜单项
        //取当前URL最后一个/后面的文件名，pop方法是删除最后一个元素并返回最后一个元素
        url = location.href.split("?")[0].split("/").pop();
      if (url) { //如果有取到，则进行匹配，否则默认首页（即index所指向的那个）
        for (var i = 0; i < links.length; i++) { //遍历menu中的链接地址
          if (links[i].href.indexOf(url) != -1) {
            index = i;
            break;
          }
        }
      }
      $(".layout>.top li:not('.line')").eq(index).addClass("active"); //给对应的<li>增加选中样式
    });
  }
  //点击退出
  function loginOut() {
    $(".loginOut").off("click").on("click", function () {
      var tableInfos = JSON.parse(localStorage.getItem("tableInfos") || "[]");
      //注释退出时检查有未上传的订单
      // var hasOrderArr = tableInfos.filter(function (m) {
      //   return m.hasOrder == 1 && m.cart && m.cart.length > 0
      // })
      // if (hasOrderArr.length > 0) {
      //   layer.open({
      //     content: "有未上传订单",
      //     btn: ["上传并退出", "直接退出"],
      //     yes: function (index) {
      //       hasOrderArr.forEach(function (v) {
      //         App.loginOutOrder(v);
      //       })
      //       layer.close(index);
      //       location.href = "../login.html"
      //       localStorage.removeItem("curTable");
      //       localStorage.removeItem("tableInfos");
      //       localStorage.removeItem("payCode");
      //       localStorage.removeItem("category_product");
      //     },
      //     no: function () {
      //       location.href = "../login.html"
      //       localStorage.removeItem("curTable");
      //       localStorage.removeItem("tableInfos");
      //       localStorage.removeItem("payCode");
      //       localStorage.removeItem("category_product");
      //     }
      //   })
      // } else {
      App.confirm("确定退出登录？", function () {
        location.href = "../login.html"
        localStorage.removeItem("curTable");
        localStorage.removeItem("tableInfos");
        localStorage.removeItem("allTables");
        localStorage.removeItem("payCode");
        localStorage.removeItem("category_product");
      })
      // }
    })
  }

    function unlocktable (table_id) {
        App.ajax("ss_wx/unlock_table", "post", {
            "table_id": table_id
        }, function (res5) {
            if (res5.flag == true) {
                location.reload();
            } else {
                App.msg(res5.msg);
            }
            if (!res5.TokenTrue) {
                App.msg("Token失效，即将跳转到登录页面", function () {
                    setTimeout(function () {
                        location.href = "../login.html";
                    }, 1000)
                })
            }
        })
    }

    function unlocktable1 (table_name) {
        App.ajax("ss_wx/unlock_table1", "post", {
            "table_name": table_name
        }, function (res5) {
            if (res5.flag == true) {
                location.reload();
            } else {
                App.msg(res5.msg);
            }
            if (!res5.TokenTrue) {
                App.msg("Token失效，即将跳转到登录页面", function () {
                    setTimeout(function () {
                        location.href = "../login.html";
                    }, 1000)
                })
            }
        })
    }

  function formatDateTime (date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    var minute = date.getMinutes();
    var seconds = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    seconds = seconds < 10 ? ('0' + seconds) : seconds;
    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+seconds;
  }

  //点击下单上传当前桌订单
  function uploadCurTable(curTable, tuicai) {
    var pay_info = [];
    var user_id = localStorage.getItem("user_id");
    curTable.cart.forEach(function (v, i) {
      var obj = {
        p_id: v.p_id,
        p_num: v.num,
        name:v.name,
        temporary_flag:v.temporary_flag,
        c_id: v.c_id,
        rsta: v.rsta ? v.rsta : 0,
        pos_order_line_id: v.pos_order_line_id ? v.pos_order_line_id : 0,
        user_id: v.user_id ? v.user_id : user_id,
        price:v.price,//单价
        uom:v.uom,
        extend_combo_flag: v.extend_combo_flag,
        totalTCPrice: parseFloat(v.totalTCPrice).toFixed(2),
        local_printer: v.local_printer,
        printer_position: v.printer_position,
        refundNum: v.refundNum ? v.refundNum: 0,
        cuisine: v.tastes ? v.tastes : v.cuisine, //加菜,如果之前下单的有做法这里要加上去
        print:(v.print?v.print:[])//打印机
      };
      if (v.combo_details && v.combo_details.length > 0) {
        obj.combo_details = v.combo_details1;
      } else {
        obj.combo_details = [];
      }

      pay_info.unshift(obj);
    });
    var order_id = curTable.order_id ? curTable.order_id : App.guid();
    let jiacai = curTable.order_id ? 1 : 0;
    let date_order = formatDateTime(new Date());
    App.ajax("ss_wx/hzg_orders", "post", {
           "pay_flag": 0,
           "pos_order": JSON.stringify({
             "order_timestamp": Date.now() + "",
             "order_id": order_id,
             "date_order": date_order,
             "jiacai": jiacai,
             "tuicai": tuicai ? 1 : 0,
             "pay_info": pay_info,
             "p_total": curTable.totalInfo.totalMon,
             "floor_id": curTable.floor_id,
             "table_id": curTable.table_id,
             "note": curTable.ZDBZ ? curTable.ZDBZ : "",
             "pay_note": "",
           })
         }, function (res) {
      if (res.flag == true) {
        curTable.order_id = res.order_id;
        curTable.origin_reference = res.origin_reference;
        curTable.order_sequence = res.order_sequence;
        curTable.hasOrder = 2;
        curTable.state = 3;
        curTable.cart.forEach(function (j, k) {
          res.pay_info.forEach(function (a, b) {
            if (j.p_id == a.p_id && j.num == a.p_num) {
              j.pos_order_line_id = a.pos_order_line_id;
              j.user_id = a.user_id;
            }
          });
          if (j.ZFname && !j.rsta) {
            j.price = j.ZFprice * 1 + j.price * 1;

          }
          if (j.combo_details && j.combo_details.length > 0 && !j.rsta) {
            j.price = j.totalTCPrice;
          }
          j.rsta = 1;

        })
        localStorage.setItem("curTable", JSON.stringify(curTable));
        var tableInfos = JSON.parse(localStorage.getItem("tableInfos") || "[]");
        if (tableInfos && tableInfos.length > 0) {
          $.each(tableInfos, function (j, k) {
            if (k.floor_id == curTable.floor_id && k.table_id == curTable.table_id) {
              tableInfos[j] = curTable;
            }
          })
          localStorage.setItem("tableInfos", JSON.stringify(tableInfos));
        }
        App.msg("下单成功", function () {

          setTimeout(function () {
            localStorage.removeItem("curTable");
             location.href = "../pages/Table.html";
          }, 1000)

        });
        var XD_pos_order = {
          "order_timestamp": Date.now() + "",
          "date_order": date_order,
          "order_id": order_id,
          "origin_reference": curTable.origin_reference?curTable.origin_reference:"",
          "order_sequence": curTable.order_sequence?curTable.order_sequence:"",
          "jiacai": jiacai,
          "tuicai": tuicai ? 1 : 0,
          "pay_info": pay_info,
          "p_total": curTable.totalInfo.totalMon,
          "floor_id": curTable.floor_id,
          "table_id": curTable.table_id,
          "m_date": curTable.m_date,
          "f_date": curTable.f_date,
          "table_name": curTable.name,
          "note": curTable.ZDBZ ? curTable.ZDBZ : "",
          "pay_note": "",
        };
        if(!jiacai){
          //第一次下单打印
          window.samfeng.MakeOrder(JSON.stringify(XD_pos_order));
        }else{
            if(tuicai){
              // return;
              //退菜打印
              window.samfeng.RefundOrder(JSON.stringify(XD_pos_order));
            } else {
              //加菜打印
              window.samfeng.AddOrder(JSON.stringify(XD_pos_order));
            }
        }
       
      } else {
        App.msg(res.msg);
        $("#XDBtn").attr("disabled", false);
      }
      if(!res.TokenTrue){
        App.msg("Token失效，即将跳转到登录页面",function () {
          setTimeout(function () {
            location.href = "../login.html";
          }, 1000)
        })
      }
    })
  }
  //退出时上传未上传订单
  function loginOutOrder(curTable) {

    var pay_info = [];
    curTable.cart.forEach(function (v, i) {
      var obj = {
        p_id: v.p_id,
        p_num: v.num,
        c_id: v.c_id
      };
      pay_info.unshift(obj);
      v.rsta = 1;
    })
    var order_id = App.guid();
    App.ajax("ss_wx/hzg_orders", "post", {
      "pay_flag": 0,
      "pos_order": JSON.stringify({
        "order_id": order_id,
        "date_order": formatDateTime(new Date()),
        "pay_info": pay_info,
        "p_total": curTable.totalInfo.totalMon,
        "floor_id": curTable.floor_id,
        "table_id": curTable.table_id
      })
    }, function (res) {
      if (res.flag == true) {
        App.msg("上传成功");
      }
      if(!res.TokenTrue){
        App.msg("Token失效，即将跳转到登录页面",function () {
          setTimeout(function () {
            location.href = "../login.html";
          }, 1000)
        })
      }
    })
  }

  function GetQueryValue(queryName) {
    var reg = new RegExp("(^|&)" + queryName + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if ( r != null ){
      return decodeURI(r[2]);
    }else{
      return null;
    }
  }

  //点击导航栏交班
  function jiaoBan() {
    $(".jiaoban").off("click").on("click", function () {
      App.confirm("确定交班？", function () {
        App.ajax("ss_wx/close_store", "post", {}, function (res) {
          if (res.flag == true) {
            // layer.open({
            //   style: "font-size:16px;",
            //   content: "交班成功",
            //   skin: 'msg',
            //   time: 1,
            //   success: function () {
            //     setTimeout(function () {
            //       location.href = "../login.html";
            //     }, 1000)
            //   }
            // })
            App.msg("交班成功", function () {
              setTimeout(function () {
                location.href = "../login.html";
              }, 1000)
            })
            localStorage.removeItem("curTable");
            localStorage.removeItem("tableInfos");
            localStorage.removeItem("allTables");
            localStorage.removeItem("payCode");
            localStorage.removeItem("category_product");
          } else {
            App.msg(res.msg)
          }
          if(!res.TokenTrue){
            App.msg("Token失效，即将跳转到登录页面",function () {
              setTimeout(function () {
                location.href = "../login.html";
              }, 1000)
            })
          }
        })
      }, function () {

      })

    })
  }

  return {
    unlocktable: unlocktable,
    unlocktable1: unlocktable1,
    uploadCurTable: uploadCurTable,
    loginOutOrder: loginOutOrder,
    loadTop: loadTop,
    GetQueryValue: GetQueryValue,
    loginOut: loginOut,
    jiaoBan: jiaoBan,
    timeBetween: timeBetween,
    formatDateTime: formatDateTime,
    alert: function (m) {
      layer.open({
        content: m,
        btn: '确定'
      });
    },
    msg: function (m, Fnsuccess) {
      layer.open({
        style: "font-size:16px;",
        content: m,
        skin: 'msg',
        time: 5, //1秒后自动关闭
        success: Fnsuccess
      })
    },
    confirm: function (m, callbackYes, callbackNo, only) {
      layer.open({
        style: "font-size:18px;",
        content: m,
        btn: only ? ['确定'] : ['确定', '取消'],
        yes: function (index) {
          if ($.isFunction(callbackYes)) {
            callbackYes();
          }
          layer.close(index);
        },
        no: function (index) {
          if ($.isFunction(callbackNo)) {
            callbackNo();
          }
          layer.close(index);
        },
        shadeClose: false
      });
    },
    fullPage: function (c, w, h) {
      var index = layer.open({
        type: 2,
        content: c,
        area: [w + 'px', h + 'px'],
        maxmin: true
      });
      layer.full(index);
    },
    iframe: function (t, w, h, c) {
      layer.open({
        type: 2,
        title: t,
        shadeClose: true,
        shade: 0.8,
        shift: 1,
        area: [w + 'px', h + 'px'],
        content: c
      });
    },
    load: function () {
      layer_index = layer.open({
        type: 2
      });
    },
    unload: function () {
      if (layer_index !== null) {
        layer.close(layer_index);
        layer_index = null;
      }
    },

    
    guid: function () {
      let d = new Date();
      let t = d.getTime();
      let year = d.getFullYear().toString();
      let Month = d.getMonth().toString();
      let Day = d.getDate().toString();
      let Hour = d.getHours().toString();
      let Min = d.getMinutes().toString();
      let Sec = d.getSeconds().toString();
      let final_time_str = year + Month + Day + Hour + Min +Sec;
      let guid = 'xxxxxx'.replace(
        /[xy]/g,
        function(c) {
          var r = (t + Math.random() * 16) % 15 | 0;
          t = Math.floor(d / 15);
          // return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
          return (c == 'x' ? r : (r & 0x7 | 0x8)).toString();
        });
      return final_time_str + guid;
    },
    ///对象数组降序排序 name 对象字段名
    by: function (name) {
      return function (o, p) {
        var a, b;
        if (typeof o === "object" && typeof p === "object" && o && p) {
          a = o[name];
          b = p[name];
          if (a === b) {
            return 0;
          }
          if (typeof a === typeof b) {
            return a < b ? 1 : -1;
          }
          return typeof a < typeof b ? 1 : -1;
        } else {
          throw ("error");
        }
      }
    },
    byDesc: function (name) {
      return function (o, p) {
        var a, b;
        if (typeof o === "object" && typeof p === "object" && o && p) {
          a = o[name];
          b = p[name];
          if (a === b) {
            return 0;
          }
          if (typeof a === typeof b) {
            return a < b ? -1 : 1;
          }
          return typeof a < typeof b ? -1 : 1;
        } else {
          throw ("error");
        }
      }
    },
    ajax: function (apiName, type, data, fnsuccess, login,loading) {
      if (typeof Object.assign != 'function') {
        // Must be writable: true, enumerable: false, configurable: true
        Object.defineProperty(Object, "assign", {
          value: function assign(target, varArgs) { // .length of function is 2
            'use strict';
            if (target == null) { // TypeError if undefined or null
              throw new TypeError('Cannot convert undefined or null to object');
            }

            var to = Object(target);

            for (var index = 1; index < arguments.length; index++) {
              var nextSource = arguments[index];

              if (nextSource != null) { // Skip over if undefined or null
                for (var nextKey in nextSource) {
                  // Avoid bugs when hasOwnProperty is shadowed
                  if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
                    to[nextKey] = nextSource[nextKey];
                  }
                }
              }
            }
            return to;
          },
          writable: true,
          configurable: true
        });
      }
      var mustData = {
        token: localStorage.getItem("token") || "",
        pos_group_id: localStorage.getItem("pos_group_id") * 1 || "",
        user_id: localStorage.getItem("user_id") * 1 || ""
      }
      $.ajax({
        type: type,
        // url: "https://dgj-test.koudailingqian.com/" + apiName,
        // url: "https://pingan.koudailingqian.com/" + apiName,
        // url: "http://192.168.31.141:8196/" + apiName,
	url: "http://47.106.8.197:8190/" + apiName,
        data: login ? data : Object.assign(data, mustData),
        dataType: "json",
        // contentType:"application/x-www-form-urlencoded",

        //ajax跨域请求不携带凭证（cookie等）
        // xhrFields: {
        //   withCredentials: true
        // },
        // crossDomain: true,
        beforeSend: function () {
        //  loading?"": App.load();
         loading?"": "";

        },
        timeout: 20000,
        success: function (result) {
          if ($.isFunction(fnsuccess)) {
            fnsuccess(result);
          }
        },
        error: function (XHR, textStatus, error) {
          if (textStatus == "timeout") {
            App.alert("请求超时，请重试");
          } else {
            App.alert("请求数据失败！");
          }
        },
        complete: function () {
        // loading?"":App.unload();
        loading?"":"";
        },
        cache:false
      });
    },
  }
}()
